﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SIA.Configurators;

namespace SIA.HwAccess.PLCSiemens
{

    public class S7Word : S7Signal, IIntegerSignal
    {
        private UInt16 _value;

        public override object Value { get { return IntValue; } set { IntValue = (int)value; } }
        
        public int IntValue
        {
            get { return (int)_value; }
            set
            {
                _connection.requestWriteData(_address, 0, BitConverter.GetBytes(value)[1]);
                _connection.requestWriteData(_address, 1, BitConverter.GetBytes(value)[0]);

                if (_value != (UInt16)value)
                {
                    _value = (UInt16)value;

                    if (this.ValueChange != null)  this.ValueChange(this);
                }
            }
        }
        public S7Word(IDictionaryProperty signalProperty, IHwConnection connection)
            : base(signalProperty, connection)
        {
            _connection.DataArrived += new ConnectionDataEvent(_connection_DataArrived);
        }
        void _connection_DataArrived(IHwConnection conn, IRawData data)
        {
            if (data.ContainsKey(_address.DataKey))
            {    
                UInt16 oldValue = _value;
                _value = BitConverter.ToUInt16(new Byte[] { data[_address.DataKey][_address.StartByte + 1], data[_address.DataKey][_address.StartByte] }, 0);
                if (oldValue != _value)
                    if (this.ValueChange != null) this.ValueChange(this);   
            }
            else
                SIA.Messages.MessageManager.sendMessage(this, "Dati non presenti nella connessione", SIA.Messages.eMessageType.DEBUG);
        }

        public override event SignalEvent ValueChange;
    }
}
